package com.gxa.hualian.web.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.hualian.entity.Coupon;
import com.gxa.hualian.entity.Manager;


import com.gxa.hualian.entity.User;
import com.gxa.hualian.service.ManagerService;
import com.gxa.hualian.service.impl.ManagerServiceImpl;
import com.gxa.hualian.util.JsonResult;
import com.gxa.hualian.util.ResponseUtil;
import com.gxa.hualian.util.StringUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ManagerServlet", urlPatterns = "/mgr")
public class ManagerServlet extends HttpServlet {
   private   ManagerService managerService=new ManagerServiceImpl();
    // 声明JsonResult对象
    private JsonResult jsonResult = new JsonResult();
    private ResponseUtil responseUtil=null;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        System.out.println("ManagerServlet 被访问了");
        // 创建ServletContext
        ServletContext servletContext = request.getServletContext();

        String encoding = servletContext.getInitParameter("encoding");

        // 接收前端的请求参数时,如果有中文, 也采用UTF-8编码格式来处理
        request.setCharacterEncoding(encoding);
        //获取请求路径

        String handlerType=request.getHeader("handlerType");
        System.out.println(handlerType);
        // 支持中文
        request.setCharacterEncoding(encoding);
        response.setContentType("application/json;charset="+encoding);
        try {
            if ("reg".equals(handlerType)){
                registerHandler(request,response);
            }else if ("login".equals(handlerType)){
                loginHandler(request,response);
            }else if("getList".equals(handlerType)){
                String name = request.getParameter("name");
                if ("".equals(name)){
                    selectByPageHandler(request,response);
                }else{
                    selectLikeNameHandler(request,response);
                }

            }else if("delete".equals(handlerType)){
                deleteHandler(request,response);
            }else if("update".equals(handlerType)){
                updateByPhoneHandler(request,response);
            }else if("add".equals(handlerType)){
                insertHandler(request,response);
            }
        }catch (Exception e){
            //当有异常发生,当前Servlet不做处理,统一转发给ExceptionServlet
            //利用request作用域对象,将e传递
            request.setAttribute("exception",e);
            //实现转发
            this.getServletContext().getRequestDispatcher("/error").forward(request,response);
        }
    }

    private void insertHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取前端json字符串
        String jsonString=request.getParameter("formData");
        //利用工具将json字符串转换为对象
        Manager manager = objectMapper.readValue(jsonString,Manager.class);
        //调用添加方法将转换的对象添加到数据库中
        manager.setInUsed(false);
        managerService.insert(manager);
        //返回前端值
        jsonResult.setCode("1");
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(response,jsonResult);
        responseUtil.write();
    }

    private void updateByPhoneHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        Integer cpnId = Integer.valueOf(request.getParameter("cpnId"));
        Boolean inUse = Boolean.valueOf(request.getParameter("inUse"));
        String phone = request.getParameter("phone");
        System.out.println(inUse);
        Manager manager = managerService.selectByPhone(phone);

        if (manager.getInUsed()==true){
            manager.setInUsed(false);
        }else{
            manager.setInUsed(true);
        }
        managerService.updateByPhone(manager);
        jsonResult.setCode("1");

        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(response,jsonResult);
        responseUtil.write();
    }

    private void deleteHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //转换
     //   Integer id=Integer.parseInt(request.getParameter("id"));
        String id = request.getParameter("id");
        String phone = request.getParameter("phone");
        System.out.println(id);


       Boolean aBoolean = managerService.deleteByPhone(phone);

        jsonResult.setCode("1");
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(response,jsonResult);
        responseUtil.write();

    }

    private void registerHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        Manager manager = new Manager();

        String phone = req.getParameter("phone");
        String smsCode=req.getParameter("captcha");

        //判读用户输入的短信验证码和服务器的是否一致
        if (!StringUtil.isEmpty(smsCode)){
            HttpSession session=req.getSession();
            Object captcha = session.getAttribute("captcha");
            System.out.println("reg captcha:"+captcha);
            if (smsCode.equals(captcha)){
                manager.setPhone(phone);
                manager.setInUsed(false);
                // 调用service操作, 必须在Servlet中(最后的管控)处理异常
                // 这个异常的处理的合理方式: 捕获
                // 原则: 不能让前端看到这个异常信息(包含大量的服务器信息) : 500状态
                // TODO 自己捕获, 根据异常信息,给前端返回加工后的数据( 服务器开小差了)
                Manager register = null;




                // 此时的注册方法,含有抛出的BusiniessException
                register = managerService.register(manager);

                //3. 向Map中添加数据
                jsonResult.setCode("1");
                //2. 声明ResponseUtil对象,完成写操作
                responseUtil = new ResponseUtil(resp,jsonResult);
                responseUtil.write();
            }


        }




    }
    private void loginHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        Manager manager=new Manager();
        String phone = req.getParameter("phone");
        System.out.println(phone);
        manager.setPhone(phone);


        managerService.login(manager);
        //3. 向Map中添加数据
        jsonResult.setCode("1");
        jsonResult.setMsg("登录成功!");
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        //写入
        responseUtil.write();

    }
    private void selectByPageHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        Integer page=Integer.parseInt(req.getParameter("page"));


        //调用业务方法
        List<Manager> lists= managerService.selectByPage(page);
        List<Manager> managers= managerService.sellectAll();

        String count= String.valueOf(managers.size());

        jsonResult.setCode("1");

        jsonResult.setData(lists);
        jsonResult.setCount(count);
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();

    }
    private void selectLikeNameHandler(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String value=request.getParameter("name");
        List<Manager> lists = managerService.selectLikeName(value);
        jsonResult.setCode("1");
        jsonResult.setData(lists);
//        String count= String.valueOf(lists.size());
//        jsonResult.setCode(count);
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(response,jsonResult);
        responseUtil.write();

    }
}
